<?php
namespace app\file\controller;

use think\Controller;
use app\file\model\WxFile;

class Up extends Controller {
	// 传入视图的参数
	private $data;
	// 公用数据获取类的实例
	private $comm;
	// accessToken
	private $accessToken;
	// common模块配置数组
	private $config;
	// 输入的数据 array
	private $in;
	public function __construct($in = [], $data = [], $comm = NULL) {
		$this->in = $in;
		$this->data = $data;
		$this->comm = $comm ? $comm : new \app\common\controller\Index ();
		if (isset ( $in ['aid'] ) && $in ['aid']) {
			$res = $this->comm->getAccessToken ( $in ['aid'] );
		} else {
			$res = $this->comm->getAccessToken ();
		}
		if ($res ['errCode']) {
			return $res;
		} else {
			$this->accessToken = $res ['data'];
		}
		$this->config = $this->comm->getConfig ();
	}
	
	/**
	 * upForeverFile2Wx
	 * 上传永久文件到微信
	 *
	 * @param array $file 文件信息数组
	 * @return mixed[] 正确，则元素data中包含微信端的url、media_id等数据
	 */
	public function upForeverFile2Wx($file = NULL) {
		/*
		 * 初始化数据
		 * 分类上传
		 * 写入数据库
		 * 返回结果
		 */
		$file = $file ? $file : $this->in;
		$data = $this->data;
		$file ['real_path'] = realpath ( ECMS_PATH . $file ['path'] . DS . $file ['name'] );
		if ('image' == $file ['type']) {
			$res = $this->upForeverImg2Wx ( $file );
		} elseif ('voice' == $file ['type']) {
		} elseif ('video' == $file ['type']) {
			$res = $this->upForeverVideo2Wx ( $file );
		}
		
		// if ($r ['type'] == 'image') {
		// $imgInfo = $this->getImageInfo ( $path );
		// $formData ['Content-Type'] = $imgInfo ['mime'];
		// }
		// $mediaData = array (
		// "type" => $r ['type'],
		// "media" => '@' . $path,
		// "form-data" => urldecode ( json_encode ( $formData ) )
		// );
		// if ($r ['type'] == "video") {
		// $mediaData ['description'] = urldecode ( json_encode ( [
		// 'title' => urlencode ( $r ['title'] ),
		// // 'thumb_media_id'=>$thumb_media_id,
		// 'introduction' => urlencode ( $r ['description'] )
		// ] ) );
		// }
		// $res = $comm->doCurl ( $url, $mediaData );
		// $res = $comm->wxErrCode ( $res );
		if (! $res ['errCode']) { // 正确上传，则将获取到的信息保存到数据库
			$r = $res ['data'];
			$r ['lifecycle'] = 'long';
			// $r ['up_to_wx_time'] = time ();永久型图片，不更新此数据
			$WxFile = new WxFile ();
			$result = $WxFile->allowField ( true )->isUpdate ( true )->save ( $r, [ 
					'id' => $file ['id'] 
			] );
			if ($result !== 1) {
				$res = [ 
						'errCode' => 509,
						'errMsg' => '文件更新出错' 
				];
			}
		}
		return $res;
	}
	/**
	 * upForeverImg2Wx
	 * 上传永久图片
	 *
	 * @param array $file 文件数据
	 * @return mixed[] 操作结果
	 */
	private function upForeverImg2Wx($file = []) {
		// 初始化数据
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		
		$url = str_replace ( 'ACCESS_TOKEN', $accessToken, $config ['wx_url'] ['up_media_forever'] );
		$url = str_replace ( 'TYPE', "image", $url );
// 		$imgInfo = $this->getImageInfo ( $file ['real_path'] );
// 		$formData ['content-type'] = $imgInfo ['mime'];
// 		$formData ['filename'] = $file ['title'];
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $file['real_path'], 'image/jpeg' )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $file['real_path']
			);
		}
		return $this->doCurl ( $url, $mediaData );
	}
	/**
	 * upForeverVideo2Wx
	 * 上传永久视频
	 *
	 * @param array $file 视频数据
	 */
	private function upForeverVideo2Wx($file = []) {
		// 初始化数据
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		
		$url = str_replace ( 'ACCESS_TOKEN', $accessToken, $config ['wx_url'] ['up_media_forever'] );
		$url = str_replace("TYPE", 'video', $url);
// 		$formData ['filename'] = urlencode ( $file ['title'] );
// 		$formData ['filelength'] = $file ['size'];
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $file['real_path'] )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $file['real_path']
			);
		}
		$mediaData ['description'] = urldecode ( json_encode ( [ 
				'title' => urlencode ( $file ['title'] ),
				// 'thumb_media_id'=>$thumb_media_id,
				'introduction' => urlencode ( $file ['description'] ) 
		] ) );
		return $this->doCurl ( $url, $mediaData );
	}
	/**
	 * upForeverVoice2Wx
	 * 上传永久音频
	 *
	 * @param array $file
	 * @return mixed[]
	 */
	private function upForeverVoice2Wx($file = []) {
		// 初始化数据
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		
		$url = str_replace ( 'ACCESS_TOKEN', $accessToken, $config ['wx_url'] ['up_media_forever'] );
		$url = str_replace("TYPE", "voice", $url);
// 		$formData ['filename'] = urlencode ( $file ['title'] );
// 		$formData ['filelength'] = $file ['size'];
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $file['real_path'] )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $file['real_path']
			);
		}
		return $this->doCurl ( $url, $mediaData );
	}
	
	/**
	 * upNewsContentImg2Wx
	 * 上传图文正文的图片到微信端
	 * 
	 * @param array $file 图片数据
	 * @return mixed[] 操作结果
	 */
	public function upNewsContentImg2Wx($file = []) {
		// 初始化数据
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		
		$url = str_replace ( 'ACCESS_TOKEN', $accessToken, $config ['wx_url'] ['up_img_for_news_content'] );
// 		$formData ['filename'] = urlencode ( $file ['title'] );
// 		$formData ['filelength'] = $file ['size'];
		$path = isset ( $file ['real_path'] ) ? $file ['real_path'] : realpath(ECMS_PATH . $file ['path'] . '/' . $file ['name']);
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $path )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $path
			);
		}
		
		$res = $this->doCurl ( $url, $mediaData );
		if (! $res ['errCode']) { // 正确上传，则将获取到的信息保存到数据库
			if(!isset($res['data']['url']) || empty($res['data']['url'])){
				return ['errCode'=>1,'errMsg'=>'不能怪我！微信给我了错误信息'];
			}
			$res ['data']['news_url'] =$res ['data']['url'];
			unset($res ['data']['url']);
			$r=$res['data'];
			$r ['lifecycle'] = 'long';
			$WxFile = new WxFile ();
			$result = $WxFile->allowField ( true )->isUpdate ( true )->save ( $r, [ 
					'id' => $file ['id'] 
			] );
			if ($result !== 1) {
				$res = [ 
						'errCode' => 509,
						'errMsg' => '文件更新出错' 
				];
			}
		}
		return $res;
	}
	/**
	 * upShortImg2Wx
	 * 上传临时图片
	 *
	 * @param array $file 文件数据
	 * @return mixed[] 操作结果
	 */
	private function upShortImg2Wx($file = []) {
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		$url = str_replace ( [ 
				'ACCESS_TOKEN',
				'TYPE' 
		], [ 
				$accessToken,
				'image' 
		], $config ['wx_url'] ['up_media_short_time'] );
		
		$formData = [ 
				'filename' => urlencode ( $file ['title'] ),
				'filelength' => $file ['size'] 
		];
		
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $file['real_path'] )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $file['real_path']
			);
		}
		return $this->doCurl ( $url, $mediaData );
	}
	/**
	 * upShortThumb2Wx
	 * 上传临时缩略图
	 * @param array $file 图片数据
	 * @return mixed[] 操作结果
	 */
	private function upShortThumb2Wx($file = []) {
		if ($file) {
			if ($file ['thumb_media_id'] and $file ['thumb_up_time'] > time () - 86400 * 3) {
				return [ 
						'errCode' => 0,
						'errMsg' => '数据库读取成功',
						'data' => $file 
				];
			} else {
				$comm = $this->comm;
				$accessToken = $this->accessToken;
				$config = $this->config;
				$url = str_replace ( [ 
						'ACCESS_TOKEN',
						'TYPE' 
				], [ 
						$accessToken,
						'thumb' 
				], $config ['wx_url'] ['up_media_short_time'] );
				$file ['real_path'] = isset ( $file ['real_path'] ) ? $file ['real_path'] : realpath ( ECMS_PATH . $file ['path'] . '/' . $file ['name'] );
				if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
					$mediaData= array (
							'media' => new \CURLFile ( $file['real_path'] )
					);
				} else {
					$mediaData= array (
							'media' => '@' . $file['real_path']
					);
				}
				$res = $this->doCurl ( $url, $mediaData );
				
				if (! $res ['errCode']) { // 正确上传，则将获取到的信息保存到数据库
					$r ['thumb_media_id'] = $res ['data'] ['thumb_media_id'];
					$r ['lifecycle'] = 'long';
					$r ['thumb_up_time'] = time ();
					$WxFile = new WxFile ();
					$result = $WxFile->allowField ( true )->isUpdate ( true )->save ( $r, [ 
							'id' => $file ['id'] 
					] );
					if ($result !== 1) {
						$res = [ 
								'errCode' => 509,
								'errMsg' => '文件更新出错' 
						];
					}
					$file['thumb_media_id']=$r ['thumb_media_id'];
					$res ['data'] =$file;
				}
				return $res;
			}
		} else {
			return [ 
					'errCode' => 508,
					'errMsg' => '未找到相应文件' 
			];
		}
	}
	/**
	 * upVoice2WxForShort
	 * 上传临时音频
	 * @abstract 待开发
	 */
	private function upShortVoice2Wx() {
	}
	
	/**
	 * upShortVideo2Wx
	 * 上传临时视频
	 * @return mixed[] 操作结果
	 */
	private function upShortVideo2Wx() {
		$comm = $this->comm;
		$config = $this->config;
		$accessToken = $this->accessToken;
		$url = str_replace ( [ 
				'ACCESS_TOKEN',
				'TYPE' 
		], [ 
				$accessToken,
				'video' 
		], $config ['wx_url'] ['up_media_short_time'] );
		
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
			$mediaData= array (
					'media' => new \CURLFile ( $file['real_path'] )
			);
		} else {
			$mediaData= array (
					'media' => '@' . $file['real_path']
			);
		}
		$mediaData ['description'] = urldecode ( json_encode ( [ 
				'title' => urlencode ( $file ['title'] ),
				'introduction' => urlencode ( $file ['description'] ) 
		] ) );
		return $this->doCurl ( $url, $mediaData );
	}
	/**
	 * upShortFile2Wx
	 * 上传临时文件到微信
	 *
	 * @param array $file 文件信息数组
	 * @return mixed[] 正确，则元素data中包含微信端的media_id等数据
	 */
	public function upShortFile2Wx($file = NULL) {
		$file = $file ? $file : $this->in;
		$data = $this->data;
		$file ['real_path'] = realpath ( ECMS_PATH . $file ['path'] . '/' . $file ['name'] );
		if ('image' == $file ['type']) {
			$res = $this->upShortImg2Wx ( $file );
		} else if ("video" == $file ['type']) {
			$res = $this->upShortVideo2Wx ( $file );
		} elseif ('thumb' == $file ['type']) {
			return $this->upShortThumb2Wx ( $file );
		}
		
		if (! $res ['errCode']) { // 正确上传，则将获取到的信息保存到数据库
			$r ['short_media_id'] = $res ['data'] ['media_id'];
			$r ['lifecycle'] = 'short';
			$r ['up_to_wx_time'] = time ();
			$WxFile = new WxFile ();
			$result = $WxFile->allowField ( true )->isUpdate ( true )->save ( $r, [ 
					'id' => $file ['id'] 
			] );
			if ($result !== 1) {
				$res = [ 
						'errCode' => 509,
						'errMsg' => '文件更新出错' 
				];
			}
		}
		return $res;
	}
	
	/**
	 * getMediaInfo
	 * 获取数据中是否已经有文件在微信端的数据
	 *
	 * @param array $r 文件数据
	 * @return mixed[] 操作结果
	 */
	private function getMediaInfo($r) {
		if (! $r)
			return [ 
					'errCode' => 508,
					'errMsg' => '未找到相应附件' 
			];
		if (! $r ['lifecycle'])
			return [ 
					'errCode' => - 1,
					'errMsg' => '未找到微信端数据' 
			];
		if ($r ['media_id']) {
			return [ 
					'errCode' => 0,
					'errMsg' => '成功在数据库中获取media_id',
					'data' => $r 
			];
		} else {
			return [ 
					'errCode' => - 1,
					'errMsg' => '未找到微信端数据' 
			];
		}
	}
	
	/**
	 * transType
	 * 转换文件类型，将中文转换为英文
	 *
	 * @param string $r 类型
	 * @return string 英文版文件类型
	 */
	private function transType($r) {
		switch ($r) {
			case '图片' :
				$r = 'image';
				break;
			case '涂鸦' :
				$r = 'image';
				break;
			case '音频' :
				$r = 'voice';
				break;
			case '视频' :
				$r = 'video';
				break;
			case '其他' :
			default :
				$r = 'music'; // 待定
		}
		return $r;
	}
	/**
	 * getImageInfo
	 * 获取图片信息
	 * @param String $url 本地图片绝对路径
	 * @return 图片信息
	 */
	private function getImageInfo($url = NULL) {
		$info = getimagesize ( $url );
		return $info;
	}
	/**
	 * doCurl
	 * 执行 curl 函数
	 * @param String $url 链接
	 * @param array|json $postField 表单数据
	 * @param number $media 是否包含多媒体文件
	 * @return mixed[]
	 */
	private function doCurl($url, $postField = NULL, $media = 1) {
		$comm = $this->comm;
		$r = $comm->doCurl ( $url, $postField, $media );
		return $r = $comm->wxErrCode ( $r );
	}
}
